package springbucks.service.impl;

import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import springbucks.dto.GradeDTO;
import springbucks.entity.Student;
import springbucks.service.LeaderBoardService;
import springbucks.util.RedisUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangyidi
 * @version V1.0
 * @Description TODO
 * @date 2022/11/23 6:44 下午
 */
@Service
public class LeaderBoardServiceImpl implements LeaderBoardService {

    @Resource
    private RedisUtil redisUtil;

    private final String GRADE_KEY = "student_grade";


    /**
     * @Description 根据学生ID 进行打分
     * @author wangyidi
     * @date 2022/11/23 5:06 下午
     * @return ResultVO
     **/
    @Override
    public void grade(GradeDTO gradeDTO, List<Student> students) {
        Student student = students.stream().filter(e->e.getId().equals(gradeDTO.getStudentId())).findFirst().get();
        student.setGrade(gradeDTO.getGrade());
        redisUtil.zsetSet(GRADE_KEY,student.getId(),gradeDTO.getGrade());
    }

    /**
     * @Description 排行榜
     * @author wangyidi
     * @date 2022/11/23 5:06 下午
     * @return ResultVO
     **/
    @Override
    public List<Student> leaderboard(List<Student> students) {

        List<Student> res = new ArrayList<>();
        Set<ZSetOperations.TypedTuple<Object>> set = redisUtil.zsetRankAll(GRADE_KEY);
        set.forEach(k->{
            res.add(students.stream().filter(e->e.getId().equals(k.getValue())).findFirst().get());
        });
        return res;
    }


}
